package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.DBmake.PostgreDB;
import com.example.demo.JsonObj.FriListObj;
import com.example.demo.JsonObj.FriendObj;
import com.example.demo.Utils.JsonUtil;
import com.example.demo.Utils.TokenUtil;
import com.example.demo.api.CommonResult;
import com.example.demo.entity.FriInfo;
import com.example.demo.entity.HeartbeatInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
public class HeartbeatController {
    @RequestMapping(value = "/Heartbeat",method = RequestMethod.POST)
    public CommonResult login(@RequestBody HeartbeatInfo heartbeatInfo){

        String token = heartbeatInfo.getToken();
        if(token==null)  return CommonResult.unauthorized("登录过期");
        if(!TokenUtil.verify(token)) return CommonResult.unauthorized("登录过期");

        int Uid = heartbeatInfo.getUid();
        PostgreDB Target = new PostgreDB();

        String FriList = Target.GetFriJson(Uid);

        if(FriList == null) return CommonResult.validateFailed();

        ArrayList<FriListObj> friListObjs = JsonUtil.getListFriend(FriList,Uid);
        String FriendJson = JSON.toJSONString(friListObjs);

        token = TokenUtil.sign(Uid);
        return CommonResult.success(FriendJson,token);
    }
}
